<script setup lang="ts">

import { ref, watch } from 'vue'
/**
 *  Audit 自定义语音播放组件
 *  @props source    语音文件
 *  @props isPlaying   是否播放
 *  @props duration  录音时长
 * */
const props = withDefaults(defineProps<{ source: string, isPlaying?: boolean, duration: Number }>(), {})
const { source, isPlaying, duration } = props
const audio = ref<HTMLAudioElement>(null)
// const duration = ref(0)
const playing = ref(false)

//  props source  、 isPlaying 是否播放
watch(() => isPlaying, (newVal) => {
  playing.value = newVal
  playAudio()
})

// 语音播放
const playAudio = () => {
  if (!audio.value && source) {
    audio.value = new Audio(source);
  }
  if (playing.value) {
    audio.value.pause();
    playing.value = false;
  } else {
    audio.value.play();
    playing.value = true;
  }
}

</script>
<template>
  <div class="voice-message " @click.stop="playAudio">
    <icon-play-circle-fill v-if="!playing" size="20" />
    <icon-pause-circle v-else :class="playing ? 'transfrom_play' : ''" />
    <span class="duration">{{ duration }} "</span>
  </div>
</template>

<style scoped lang="scss">
.voice-message {
  display: flex;
  align-items: center;
  cursor: pointer;
  background-color: var(--color-neutral-6);
  color: rgb(var(--arcoblue-5));
  height: 32px;
  padding: 5px 10px !important;
  margin: 5px 40px;
  border-radius: 4px;
}

.arco-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 10px;
  opacity: 0.5;
  transition: opacity 0.3s;
}

.icon.active {
  opacity: 1;
}

.duration {
  font-size: 14px;
  color: var(--color-neutral-6);
}

.icon.active {
  animation: pulse 1s infinite alternate;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  100% {
    transform: scale(1.2);
  }
}
</style>
